package com.network.service;

import com.network.dao.UserDao;
import com.network.entity.Dept;
import com.network.entity.User;
import com.network.qo.UserQo;
import com.network.util.CommonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * @author peng
 */
@Service
@CacheConfig(cacheNames = {"userCache"})
public class UserService
{


    @Autowired
    private UserDao userDao;


    public User saveUser(User user)
    {
       return  userDao.save(user);
    }

    /**
     * 用户登录
     * @param userName
     * @param password
     * @return
     */
    public User login(String userName,String password)
    {
       return userDao.findByUsernameAndPassword(userName,password);
    }

    //根据用户名获取用户
    @Cacheable(key ="targetClass + methodName +#p0")
    public CompletableFuture<User> findByUserName(String userName)
    {
        return CompletableFuture.supplyAsync(() -> {
            return  userDao.findFirstByUsername(userName);
        });

    }

    public Page<User> findByPage(UserQo userQo)
    {
        //根据创建时间排序
        Sort sort=new Sort(Sort.Direction.DESC,"createTime");

        Pageable pageable=new PageRequest(userQo.getPage(),userQo.getLimit(),sort);

       return userDao.findAll((root, query, criteriaBuilder) -> {

           List<Predicate> predicateList=new ArrayList<Predicate>();

           Join<User, Dept> expressJoin= root.join("dept", JoinType.INNER);
           if (CommonUtils.isNotNull(userQo.getUsername()))
           {
               predicateList.add(criteriaBuilder.like(root.get("userName"),"%"+userQo.getUsername()+","));
           }
           if (CommonUtils.isNotNull(userQo.getDept()))
           {
               predicateList.add(criteriaBuilder.equal(expressJoin.get("id"),userQo.getDept().getId()));
           }
           query.where(predicateList.toArray(new Predicate[predicateList.size()]));
           return query.getRestriction();
       },pageable);
    }
}











